<template>
  <a-modal
      :title="`角色授权（${fields.name}）`"
      centered
      :width="720"
      :bodyStyle="{maxHeight: '80vh',overflow: 'auto'}"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :afterClose="remove"
      @ok="handleOk"
  >
    <a-tree
        checkable
        :selectable="false"
        v-model:checkedKeys="checkedKeys"
        v-model:expandedKeys="expandedKeys"
        checkStrictly
        @check="onCheck"
        :tree-data="treeData"
    />
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs, ref} from 'vue'
import {Modal, Tree} from 'ant-design-vue'
import {addSchema} from "./add-schema"
import {useAsync} from "@/hooks"
import DynamicForm from '@/components/dynamic-form/dynamic-form.vue'
import {roleAuth} from "@/api/role/roles"
import {permissionGetPerbyId} from '@/api/role/permission'

export default defineComponent({
  name: "auth-modal",
  components: {
    [Modal.name]: Modal,
    [Tree.name]: Tree,
  },
  props: {
    remove: { // 移除模态框
      type: Function
    },
    fields: {
      type: Object,
      required: true
    },
    permissions: {
      type: Array,
      default: () => []
    },
    callback: {
      type: Function,
      required: true
    }
  },
  setup(props) {

    const state = reactive({
      visible: true,
      confirmLoading: false,
      treeData: [] as any[],
      expandedKeys: [],
      checkedKeys: {
        checked: [] as number[],
        halfChecked: []
      }
    })

    // 数组转树形结构
    const arr2tree = (items, id = 1, parent = 'pid') => {
      return items.filter(item => item[parent] == id).map(item => ({
        ...item,
        key: item.id,
        children: arr2tree(items, item.id)
      }))
    }

    // 获取跟节点
    state.treeData = props.permissions.filter((item: any) => item.pid === undefined || item.pid === null || item.pid === 0).map((item: any) => ({
      ...item,
      key: item.id,
      children: []
    }))
    // 往根节点添加子节点
    state.treeData[0].children = arr2tree(props.permissions, state.treeData[0].id)
    // console.log(props.permissions, 'props.permissions')
    // console.log(state.treeData, '问问防守打法')
    // 默认选中
    state.checkedKeys.checked = props.fields.perids?.split(',').map(id => ~~id)
    // 默认展开
    state.expandedKeys = props.permissions.map((item: any) => item.id) as any

    // 全选或取消全选
    const treeForeach = (tree, func, key = 'children') => {
      tree.forEach(item => {
        func(item)
        item[key]?.length && treeForeach(item[key], func)
      })
    }

    // 父节点找找看
    const getParentNodeKey = (vcTreeNode, func) => {
      if (vcTreeNode.vcTreeNode) {
        func(vcTreeNode.eventKey) && getParentNodeKey(vcTreeNode.vcTreeNode, func)
      }
    }
    // 勾选节点时触发
    const onCheck = (checkedKeys, e) => {
      const {checked, checkedNodes, node, event} = e
      // 当前节点的所有子节点
      const children = node.dataRef.children
      if (checked) { // 勾选
        treeForeach(children, (item) => {
          state.checkedKeys.checked = checkedKeys.checked.concat([item.key])
        })
        state.checkedKeys.checked = state.checkedKeys.checked.concat([node.vcTreeNode.eventKey])
        console.log(node, 'wokao')
        // 如果勾选了子节点，则父节点也必须勾选
        getParentNodeKey(node.vcTreeNode, (eventKey) => state.checkedKeys.checked.push(eventKey))
      } else { // 取消勾选
        treeForeach(children, (item) => {
          state.checkedKeys.checked = checkedKeys.checked.filter(n => n != item.key)
        })
      }
      // 上面操作完后，再去重一次
      state.checkedKeys.checked = [...new Set(state.checkedKeys.checked)]
    }

    console.log(props.fields.perids?.split(','), '这啊')
    const handleOk = async () => {
      state.confirmLoading = true
      const params = {
        id: props.fields.id,
        perids: [...new Set(state.checkedKeys.checked)]
      }
      console.log(params.perids.length, '啊这')
      await roleAuth(params)
      state.confirmLoading = false
      state.visible = false
      props.callback()
    }

    return {
      ...toRefs(state),
      handleOk,
      onCheck
    }
  }
})
</script>

<style lang="scss" scoped>
::v-deep(.ant-card) {
  height: 100%;

  .ant-checkbox-wrapper {
    margin-left: 0;
  }
}
</style>
